﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Linq;
using OctoOS;
using OctoOS.UI;
using System.Web.UI.WebControls;

public partial class category : OOSPage
{
    class PathInfo
    {
        [PathInfoMember(0)]
        internal long categoryID;

        [PathInfoMember(1, true)]
        internal int pageIndex;

        [PathInfoMember(2, true)]
        internal int isRadios;

        [PathInfoMember(3, true)]
        internal int miles;

        [PathInfoMember(4, true)]
        internal int adType = 2;

        [PathInfoMember(5, true)]
        internal int isPictures;

        [PathInfoMember(6, true)]
        internal int sortMode;

        [PathInfoMember(7, true)]
        internal string attributes;

        internal void PostInit()
        {
            if (pageIndex > 0)
            {
                pageIndex--;
            }
        }
    }


    int _adsOnPage = 2;
    int _startIndex = 0;
    Resource _resource = null;
    PathInfo _pathInfo;
    Category _currentCategory = null;
    Category[] _allCategories = new Category[] {};
    List<long> _categoryIDs = new List<long>(); // list of parent categories IDs
    ClassifiedAd[] _ads = new ClassifiedAd[] {};
    Attribute[] _att = new Attribute[] { };

    protected void Page_Init(object sender, EventArgs e)
    {
        _pathInfo = EnablePathInfo<PathInfo>();
        Helper.Categories.UpdateCategoryCache();
    }

    private void SetBreadcrumbsAndActions()
    {
        _resource = DataSource.ClassifiedResources_Get(
            OOSRequest.Current.ResourceID);
        AddBreadcrumb(string.Empty, "/");
        Category parentCategory = Helper.Categories.GetParentCategory(_pathInfo.categoryID);
        Category grandParentCategory = Helper.Categories.GetGrandParentCategory(_pathInfo.categoryID);

        if (grandParentCategory != null)
        {
            AddBreadcrumb(grandParentCategory.Name, Urls.Classifieds.GetCategoryInfo(grandParentCategory.ID));
        }
        if (parentCategory != null)
        {
            AddBreadcrumb(parentCategory.Name, Urls.Classifieds.GetCategoryInfo(parentCategory.ID));
        }

        if (OOSRequest.Current.IsAuthenticated || _resource.AllowAnonAds)
        {
            if (_currentCategory.ReadOnly)
            {
                if (parentCategory != null)
                {
                    AddAction("Add New Ad", Urls.Classifieds.GetSelect(parentCategory.ID, _currentCategory.ID));
                }
                else
                {
                    AddAction("Add New Ad", Urls.Classifieds.GetSelect(_currentCategory.ID));
                }
            }
            else
            {
                AddAction("Add New Ad", Urls.Classifieds.GetAddNewAd(0, _currentCategory.ID));
            }
        }
    }

    private void BuildCategoryTree()
    {
        foreach (var childCat in _allCategories.Where(f => f.ParentCategoryID == _currentCategory.ID))
        {
            _categoryIDs.Add(childCat.ID);
            TextTreeNode childNode = new TextTreeNode(childCat.Name);
            childNode.HRef = Urls.Classifieds.GetCategoryInfo(childCat.ID);
            foreach (var grandChildCat in _allCategories.Where(f => f.ParentCategoryID == childCat.ID))
            {
                _categoryIDs.Add(grandChildCat.ID);
                TextTreeNode grandChildNode = new TextTreeNode(grandChildCat.Name);
                grandChildNode.HRef = Urls.Classifieds.GetCategoryInfo(grandChildCat.ID);
                childNode.Nodes.Add(grandChildNode);
            }
            CategoryTree.Nodes.Add(childNode);
        }
    }

    private void ShowAttributes()
    {
        _att = DataSource.ClassifiedAttributes_GetByCategory(
                _pathInfo.categoryID);
        foreach (var attribute in _att.Where(f => !f.IsCustom))
        {
            FormRow row = new FormRow();
            row.ID = "Row_" + attribute.ID;
            row.Label = attribute.Title;
            var ddl = new DropDownList();
            ddl.ID = "Ddl_" + attribute.ID;
            ddl.Items.Add(new ListItem("All", "0"));
            foreach (var value in attribute.AttributeValues)
            {
                ddl.Items.Add(new ListItem(value.AttributeValueName, value.AttributeValue.ToString()));
            }
            row.Controls.Add(ddl);
            FormView.Controls.Add(row);
        }

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _startIndex = _pathInfo.pageIndex * _adsOnPage;

        _categoryIDs.Add(_pathInfo.categoryID);

        _allCategories = Helper.Categories.GetAllCategories();

        _currentCategory = Helper.Categories.GetCategory(_pathInfo.categoryID);
        if (_currentCategory != null)
        {
            PageTitle = _currentCategory.Name;

            BuildCategoryTree();

            ShowAttributes();

            // add submit button
            FormRow submitRow = new FormRow();
            Submit s = new Submit();
            s.Click += new EventHandler(s_Click);
            submitRow.Controls.Add(s);
            FormView.Controls.Add(submitRow);
        }
        else
        {
            throw new HttpException(404, "This category doesnt exist");
        }

        SetBreadcrumbsAndActions();

        if (!IsPostBack)
        {
            // setting controls from PathInfo
            Radios.Checked = Convert.ToBoolean(_pathInfo.isRadios);
            Miles.Value = _pathInfo.miles;
            Adtype.SelectedValue = _pathInfo.adType.ToString();
            pictures.Checked = Convert.ToBoolean(_pathInfo.isPictures);
            SortMode.SelectedValue = _pathInfo.sortMode.ToString();
            //parsing and setting attributes
            if (!String.IsNullOrEmpty(_pathInfo.attributes))
            {
                string[] attributes = _pathInfo.attributes.Split(new char[] { '|' });
                foreach (string attr in attributes)
                {
                    string atID = attr.Substring(0, attr.IndexOf('_'));
                    string valID = attr.Substring(attr.IndexOf('_') + 1);
                    Control row = FormView.FindControl("Row_" + atID);
                    if (row != null)
                    {
                        Control ddl = row.FindControl("Ddl_" + atID);
                        if (ddl != null)
                        {
                            (ddl as DropDownList).SelectedValue = valID;
                        }
                    }
                }
            }

            // getting ads list
            int totalCnt;
            _ads = DataSource.ClassifiedAds_Search(
                OOSRequest.Current.ResourceID,
                Radios.Checked,
                Miles.ValueAsInt32,
                Convert.ToByte(Adtype.SelectedValue),
                pictures.Checked,
                GetSelectedAttributes(),
                Convert.ToByte(SortMode.SelectedValue),
                _categoryIDs.ToArray(),
                _startIndex,
                _adsOnPage,
                out totalCnt);
            if (_ads.Count() > 0)
            {
                ShowFoundAds(_ads);
                int pageMaxCnt = Convert.ToInt32(Math.Ceiling((double)totalCnt/_adsOnPage));
                adsNumericPager.PageCount = pageMaxCnt;
                adsNumericPager.SelectedIndex = _pathInfo.pageIndex;
                adsNumericPager.PageUrlPattern = Urls.Classifieds.GetCategoriesPageUrlPattern(_pathInfo.categoryID, Radios.Checked,
                    Miles.ValueAsInt32, Adtype.SelectedValue, pictures.Checked, SortMode.SelectedValue, GetSelectedAttributesAsString());
                adsNumericPager.FirstPageUrl = Urls.Classifieds.GetCategoriesFirstPageUrlPattern(_pathInfo.categoryID, Radios.Checked,
                    Miles.ValueAsInt32, Adtype.SelectedValue, pictures.Checked, SortMode.SelectedValue, GetSelectedAttributesAsString());
            }
            else
            {
                infoMsgBox.Visible = true;
                infoMsgBox.SetContent("There are no found ads");
            }
        }
        
    }

    private ObjectPreview GetObjectPreview(ClassifiedAd ad)
    {
        Image48ObjectPreview pr = new Image48ObjectPreview();
        pr.ImageUrl = "/Images/email_icon.jpg";
        pr.HeaderText = ad.Title;
        pr.HeaderUrl = Urls.Classifieds.GetInfoAd(ad.ID);
        pr.Footer = new OctoOS.UI.Literal(GetCategoriesFooter(ad.CategoryID));
        if (ad.AdText.Length > 20)
        {
            pr.Body = new OctoOS.UI.Literal(ad.AdText.Substring(0, 20) + "...");
        }
        else
        {
            pr.Body = new OctoOS.UI.Literal(ad.AdText + "...");
        }
        return pr;
    }

    private string GetCategoriesFooter(long categoryID)
    {
        string result;
        Category grandCat = null;
        Category parentCat = null;
        Category cat = _allCategories.First(f => f.ID == categoryID);
        result = cat.Name;
        if (cat.ParentCategoryID != 0)
        {
            parentCat = _allCategories.First(f => f.ID == cat.ParentCategoryID);
            result = parentCat.Name + " -> " + result; 
            if (parentCat.ParentCategoryID != 0)
            {
                grandCat = _allCategories.First(f => f.ID == parentCat.ParentCategoryID);
                result = grandCat.Name + " -> " + result;
            }
        }
        return "Category: " + result;
    }


    void s_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Response.Redirect(Urls.Classifieds.GetCategoriesFirstPageUrlPattern(_pathInfo.categoryID, Radios.Checked,
            Miles.ValueAsInt32, Adtype.SelectedValue, pictures.Checked, SortMode.SelectedValue, GetSelectedAttributesAsString()));
        }
    }

    private void ShowFoundAds(ClassifiedAd[] ads)
    {
        foreach (var ad in ads)
        {
            OctoOS.UI.ListViewItem row = new OctoOS.UI.ListViewItem();
            row.Controls.Add(GetObjectPreview(ad));
            ListView.Controls.Add(row);
        }
    }

    private SelectedAttribute[] GetSelectedAttributes()
    {
        List<SelectedAttribute> sel = new List<SelectedAttribute>();
        foreach (var row in FormView.Controls)
        {
            if ((row is FormRow) && (row as FormRow).ID != null && (row as FormRow).ID.ToLower().Contains("row_"))
            {
                foreach (var ddl in (row as FormRow).Controls)
                {
                    if ((ddl is DropDownList) && (ddl as DropDownList).ID.ToLower().Contains("ddl_"))
                    {
                        byte value = Convert.ToByte((ddl as DropDownList).SelectedValue);
                        if (value != 0)
                        {
                            sel.Add(
                                new SelectedAttribute
                                {
                                    AttributeID = Convert.ToInt64((ddl as DropDownList).ID.Substring(4)),
                                    AttributeValue = value
                                });

                        }
                    }
                }
            }
        }
        return sel.ToArray();
    }

    private string GetSelectedAttributesAsString()
    {
        string result = "";
        SelectedAttribute[] attributes = GetSelectedAttributes();
        foreach (var att in attributes)
        {
            if (result != "")
            {
                result += "|";
            }
            result += att.AttributeID + "_" + att.AttributeValue;
        }
        return result;
    }
}